package tiled.mapeditor.util;

import java.awt.*;
import java.util.HashMap;
import javax.swing.*;

import tiled.core.Tile;
import tiled.core.TileSet;
import tiled.mapeditor.Resources;

public class MultisetListRenderer extends DefaultListCellRenderer
{
    private final Icon setIcon = Resources.getIcon("source.png");

    private final HashMap<Integer, Icon> tileImages = new HashMap<Integer, Icon>();

    private final double zoom;

    public MultisetListRenderer(double zoom)
    {
        this.zoom = zoom;
    }

    public Component getListCellRendererComponent(JList list, Object value,
                                                  int index, boolean isSelected,
                                                  boolean cellHasFocus)
    {
        super.getListCellRendererComponent(list, value, index,
                isSelected, cellHasFocus);

        if (value instanceof Tile && index >= 0)
        {
            Tile tile = (Tile)value;
            if (!isSelected || zoom == 1)
            {
                if (tileImages.containsKey(index))
                {
                    setIcon(tileImages.get(index));
                }
                else
                {
                    Icon icon = new ImageIcon(tile.getScaledImage(zoom));
                    setIcon(icon);
                    tileImages.put(index, icon);
                }
            }
            else
            {
                setIcon(new ImageIcon(tile.getImage()));
            }
        }
        else if (value instanceof TileSet)
        {
            setIcon(setIcon);
        }

        return this;
    }
}
